<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@ page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.*" %>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Edit Department</title>
	
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
	<link rel="stylesheet" type="text/css" href="css/student-system.css" />
	<link rel="stylesheet" type="text/css" href="css/frame.css" />
	
	<style type="text/css">
		td {
			height: 50px;
		}
		
		input {
			font-size: 20px;
		}
		
		select {
			font-size: 20px;
		}
		
		a {
	      text-decoration:none;
	   }
	</style>
</head>
<body>

<%
	//get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
	
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	
	<%}
	
	// get parameter	
	String departmentId = request.getParameter("departmentId");
	String departmentNameENOld = request.getParameter("departmentNameEN");
	String departmentNameTHOld = new String(request.getParameter("departmentNameTH").getBytes("ISO8859_1"),"UTF-8");
	String departmentNameShortOld = request.getParameter("departmentNameShort");
			
	System.out.println("EDIT departmentID "+departmentId);////////try////////
	System.out.println("EDIT departmentNameENOld "+departmentNameENOld);////////try////////
	System.out.println("EDIT departmentNameTHOld "+departmentNameTHOld);////////try////////
	System.out.println("EDIT departmentNameShortOld "+departmentNameShortOld);////////try////////


	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620" );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
%>

	<div id="page-wrap">
			<div id="inside">
				<table border="0">
					<tr style="font-size:24px">
						<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
							<div id="header_banner-2"></div>
						</td>
						
						<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
							<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
							<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
						</td>
					</tr>
				</table>
        		
        		<div id="main-content-ac">
        					<div class="imageFrame">แก้ไขภาควิชา</div>
						
							<br/><br/><br/><br/><br/>
        						<center>
        						
	        						<table border="0" width="800">  
										<tr style="font-size:20px">	
											<form id="form" name="form" method="post" action="">
												<input type="hidden" id="departmentId" name="departmentId" value="<%=departmentId%>" /> 
												
												<td>
													<label for="labelDepartmentTH"> <font size="5"><strong>ภาควิชา (ภาษาไทย)</strong></font> </label>
													<label><font size="5" color="#FF0000">*</font></label>
												</td>
												<td>
													<input type="text" name="departmentTH" id="departmentTH" value="<%=departmentNameTHOld%>" />  
												</td>
												<input type="hidden" id="departmentNameTH" name="departmentNameTH" value="<%=departmentNameTHOld%>" /> 
										</tr>
			
										<tr style="font-size:20px">
												<td>
													<label for="labelDepartmentEN"> <font size="5"><strong>ภาควิชา (ภาษาอังกฤษ)</strong></font> </label>
													<label><font size="5" color="#FF0000">*</font></label>
												</td>
												<td>
													<input type="text" name="departmentEN" id="departmentEN" value="<%=departmentNameENOld%>" />  
												</td>
												<input type="hidden" name="departmentNameEN" id="departmentNameEN" value="<%=departmentNameENOld%>" />
										</tr>
										
										<tr style="font-size:20px">
												<td>
													<label for="labelDepartmentShort"> <font size="5"><strong>ตัวย่อภาควิชา</strong></font> </label>
													<label><font size="5" color="#FF0000">*</font></label>
												</td>
												<td>
													<input type="text" name="departmentShort" id="departmentShort" value="<%=departmentNameShortOld%>" /> 
												</td>
										</tr>
										
										<td colspan="2">
						            		<label><font size="3" color="#FF0000">หมายเหตุ: * คือ ข้อมูลสำคัญ จำเป็นต้องกรอก</font></label>
						            	</td>
	
										<tr>
											<td>
													<center><input type="submit" value="save" name="save" class="buttonStyle"/></center>
													</form>
											</td>
											
											<td>
													<center><a href="admin_department.jsp"><button class="buttonStyle"/>cancel</button></a></center> 
												
											</td>
										</tr>
									</table>
								
								</center>
							
						<br><br><br>
						
					<div style="clear: both;"></div>
						<div id="footer"></div>
			</div>		
						<div style="clear: both;"></div>		
	</div>
	
<%
		String checkButton = request.getParameter("save");
		System.out.println("checkButton : "+checkButton);////////////////////try///////////////////
		// check save button is pressed
		if("save".equals(checkButton)) {

				//request.setCharacterEncoding("UTF-8");
				
				// get value from tag
				String departmentNameTHNew = new String(request.getParameter("departmentTH").getBytes("ISO8859_1"),"UTF-8");
				String departmentNameENNew = request.getParameter("departmentEN");
				String departmentNameShortNew = request.getParameter("departmentShort");
				
				System.out.println("departmentTH +++++++++ : "+departmentNameTHNew);////////////////////try///////////////////
				System.out.println("departmentEN NEW : "+departmentNameENNew);////////////////////try///////////////////
				System.out.println("departmentEN OLD : "+departmentNameENOld);////////////////////try///////////////////
				System.out.println("departmentShort NEW : "+departmentNameShortNew);////////////////////try///////////////////
				System.out.println("departmentShort OLD : "+departmentNameShortOld);////////////////////try///////////////////
				
				System.out.println("SAME EN "+departmentNameENNew.equals(departmentNameENOld));////////////////////try///////////////////
				System.out.println("SAME TH "+departmentNameTHNew.equals(departmentNameTHOld));////////////////////try///////////////////
				System.out.println("SAME SH "+departmentNameShortNew.equals(departmentNameShortOld));////////////////////try///////////////////
				// check special character
			   	Pattern regex = Pattern.compile("[$&+,:;=?@#^*<>)(|!%]");
			   	Matcher matcherdepartmentNameTH = regex.matcher(departmentNameTHNew);
			   	Matcher matcherdepartmentNameEN = regex.matcher(departmentNameENNew);
			 	Matcher matcherdepartmentNameShort = regex.matcher(departmentNameShortNew);
			   	if (matcherdepartmentNameTH.find() || matcherdepartmentNameEN.find() || matcherdepartmentNameShort.find()){
				%>
								<script language="javascript"> alert("กรุณาใส่ตัวอักษรหรือตัวเลขเท่านั้น");	</script>
				<%}else{

				if(!departmentNameTHNew.equals(departmentNameTHOld) || !departmentNameENNew.equals(departmentNameENOld) || !departmentNameShortNew.equals(departmentNameShortOld)) {
					try {					
						// check department name exist
						ResultSet rs = connect.createStatement().executeQuery("SELECT department_name_th "
													+ " FROM department "
													+ " WHERE department_name_th='"+departmentNameTHNew+"'");
						
						rs.last();
						if(rs.getRow() == 1) {
		%>
							<script language="javascript"> alert("ภาควิชานี้มีอยู่ในระบบแล้ว กรุณากรอกใหม่อีกครั้งค่ะ");	</script>
		<%								
						}
						else {
							String sql = "UPDATE `department` SET `department_name_th`='"+ departmentNameTHNew + "', "
									+ " `department_name_en`='" + departmentNameENNew + "', "
									+ " `department_name_short`='" + departmentNameShortNew + "' "
									+ " WHERE department_id="+departmentId;
							
							connect.createStatement().executeUpdate(sql);
						
							
							/* Log file */						
							String log = "admin edit department";
							Log.writeAdminFile(log);
							Log.writeAdminFile(sql);
							
	%>
							<script language="javascript"> alert("บันทึกข้อมูลสำเร็จ");	</script>
							<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_department.jsp">
							
	<%
						}
					} catch (SQLException e) {
						e.printStackTrace();
		%>
						<script language="javascript"> alert("มีข้อผิดพลาดเกิดขึ้น กรุณาลองใหม่อีกครั้งค่ะ");	</script>
		<%
					}				
				}
				else {
%>
					<script language="javascript"> alert("ข้อมูลไม่มีการเปลี่ยนแปลง กรุณาตรวจสอบอีกครั้งค่ะ");	</script>			
<%
				}
			}
			   	
			   	connect.close();
		}
%>

</body>
</html>